<?php
namespace c\img;

/**
 * 读取远程图片
 *
 * @author YeFng
 */
class remote extends b
{
	//分析链接
    function content_match($str)
    {
        set_time_limit(120);
        preg_match_all ("|<img .*?src=['\"]?+([^'\" ]+)|is", $str, $arr);
        $arr = array_unique($arr[1]);
        
        foreach($arr as $url)
          {
            if (!preg_match("/^http:|^https:/", $url)) 
                continue;
            if(strpos($url, ROOT_URL)===0)
                 continue;
            
            $newPath = $this->copy($url);
            if ($newPath)
             {
                $newPath = htmlq(\url::g('u=cimg\b&q='. \encrypt::q_ed( 'f='. $newPath)));
                $str = str_replace($url, $newPath, $str);
             }
          }
        return $str;
    }
    function copy($url)
    {
        $ext = $this->F->get_ext($url);
        $dir = date('Y/m/');
        $fileName = \YF_f::initC('\c\file\upload')->buildFile($dir,  uniqid() . '.'. $ext);
        $f = FILE_DIR . $dir . $fileName;
        $path = $dir. $fileName;
        
        if (in_array(strtolower($ext), array('jpg','jpeg','gif','png')) )
         {
            $str = $this->F->r_file($url);
            if (!$str)return false;
            
            if ($this->F->w_file($f, $str))
               return $path;
         }
        else{
			//未知文件名
            if ($this->imOut($f,  $this->im($url)))
                return $path;
         }
         
        unlink($f);
        return false;
    }
}
